document.addEventListener('DOMContentLoaded', () => {
    const notesContainer = document.getElementById('notesContainer');
    const addNoteBtn = document.getElementById('addNoteBtn');
    const titleInput = document.getElementById('titleInput');
    let notes = JSON.parse(localStorage.getItem('notes')) || [];
    let draggedNote = null;
    let initialX, initialY;
    let isDragging = false;

    // 初始化标题
    const savedTitle = localStorage.getItem('noteTitle');
    if (savedTitle) {
        titleInput.value = savedTitle;
    }

    // 保存标题
    titleInput.addEventListener('input', () => {
        localStorage.setItem('noteTitle', titleInput.value);
    });

    // 初始化便利贴
    notes.forEach(note => {
        createNoteElement(note);
    });

    // 添加新便利贴
    addNoteBtn.addEventListener('click', () => {
        const newNote = {
            id: Date.now(),
            content: '',
            color: '#ffffff',
            x: Math.random() * (window.innerWidth - 250),
            y: Math.random() * (window.innerHeight - 200)
        };
        notes.push(newNote);
        saveNotes();
        createNoteElement(newNote);
    });

    // 创建便利贴元素
    function createNoteElement(note) {
        const noteElement = document.createElement('div');
        noteElement.className = 'note';
        noteElement.style.backgroundColor = note.color;
        noteElement.dataset.id = note.id;
        noteElement.style.left = `${note.x || 0}px`;
        noteElement.style.top = `${note.y || 0}px`;

        noteElement.innerHTML = `
            <textarea placeholder="在这里输入内容...">${note.content}</textarea>
            <button class="delete-btn">×</button>
            <div class="note-color">
                <div class="color-option" style="background-color: #ffffff" data-color="#ffffff"></div>
                <div class="color-option" style="background-color: #ffcccc" data-color="#ffcccc"></div>
                <div class="color-option" style="background-color: #ccffcc" data-color="#ccffcc"></div>
                <div class="color-option" style="background-color: #ccccff" data-color="#ccccff"></div>
                <div class="color-option" style="background-color: #ffffcc" data-color="#ffffcc"></div>
            </div>
        `;

        const textarea = noteElement.querySelector('textarea');
        const deleteBtn = noteElement.querySelector('.delete-btn');

        // 添加拖拽功能
        noteElement.addEventListener('mousedown', (e) => {
            // 如果点击的是文本框或删除按钮，不触发拖拽
            if (e.target === textarea || e.target === deleteBtn) {
                return;
            }
            startDrag.call(noteElement, e);
        });

        noteElement.addEventListener('touchstart', (e) => {
            if (e.target === textarea || e.target === deleteBtn) {
                return;
            }
            startDrag.call(noteElement, e);
        });

        // 添加删除功能
        deleteBtn.addEventListener('click', () => {
            notes = notes.filter(n => n.id !== note.id);
            saveNotes();
            noteElement.remove();
        });

        // 添加内容保存功能
        textarea.addEventListener('input', (e) => {
            const noteIndex = notes.findIndex(n => n.id === note.id);
            notes[noteIndex].content = e.target.value;
            saveNotes();
        });

        // 添加颜色更改功能
        noteElement.querySelectorAll('.color-option').forEach(colorOption => {
            colorOption.addEventListener('click', (e) => {
                const color = e.target.dataset.color;
                noteElement.style.backgroundColor = color;
                const noteIndex = notes.findIndex(n => n.id === note.id);
                notes[noteIndex].color = color;
                saveNotes();
            });
        });

        notesContainer.appendChild(noteElement);
    }

    function startDrag(e) {
        isDragging = true;
        draggedNote = this;
        draggedNote.classList.add('dragging');

        const rect = draggedNote.getBoundingClientRect();

        if (e.type === 'mousedown') {
            initialX = e.clientX - rect.left;
            initialY = e.clientY - rect.top;
            document.addEventListener('mousemove', drag);
            document.addEventListener('mouseup', stopDrag);
        } else {
            initialX = e.touches[0].clientX - rect.left;
            initialY = e.touches[0].clientY - rect.top;
            document.addEventListener('touchmove', drag);
            document.addEventListener('touchend', stopDrag);
        }
    }

    function drag(e) {
        if (!draggedNote || !isDragging) return;

        let x, y;

        if (e.type === 'mousemove') {
            x = e.clientX - initialX;
            y = e.clientY - initialY;
        } else {
            x = e.touches[0].clientX - initialX;
            y = e.touches[0].clientY - initialY;
        }

        // 移除位置限制，允许在全屏幕范围内移动
        draggedNote.style.left = `${x}px`;
        draggedNote.style.top = `${y}px`;

        // 更新存储的位置
        const noteIndex = notes.findIndex(n => n.id === parseInt(draggedNote.dataset.id));
        if (noteIndex !== -1) {
            notes[noteIndex].x = x;
            notes[noteIndex].y = y;
            saveNotes();
        }
    }

    function stopDrag() {
        if (!draggedNote) return;
        isDragging = false;
        draggedNote.classList.remove('dragging');
        draggedNote = null;
        document.removeEventListener('mousemove', drag);
        document.removeEventListener('mouseup', stopDrag);
        document.removeEventListener('touchmove', drag);
        document.removeEventListener('touchend', stopDrag);
    }

    // 保存便利贴到本地存储
    function saveNotes() {
        localStorage.setItem('notes', JSON.stringify(notes));
    }
}); 